<?php
/**
 * Контроллер разделов сайта административной панели
 * 
 * @category Phorm
 * @package Controller_Module_Control
 * @name /Phorm/Controller/Module/Control/Categories.php
 * @copyright phorm.ru
 * @since 05.05.2012
 * @author vladimir@kachalov.net
 */

class Phorm_Controller_Module_Control_Categories extends Phorm_Controller_Controller {
	
	/**
	 * Экземпляр класса разделов
	 * @var Phorm_Categories
	 */
	public $Categories;
	
	
	/**
	 * Предиспетчер
	 * 
	 * @return void
	 */
		
	public function preDispatch() {
		
		$this->Categories = new Phorm_Categories();
		
	}
	
	/**
	 * Список разделов
	 * 
	 * @return void
	 */
		
	public function indexAction() {
		
		
	}
	
	
	/**
	 * Информация о разделе
	 * 
	 * @return void
	 */
		
	public function viewAction() {
		
		if(isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			$CategoryInfo['acl'] = array(
				'mvc' => $this->_usersession->UserData['acl']['mvc']['control']['categories'],
				'category' => $this->_usersession->UserData['acl']['categories'][$CategoryInfo['categoryid']]
			);
			
			$this->view->assign("CategoryInfo",$CategoryInfo);
			$this->view->assign("Header",$CategoryInfo['categoryname']);
			
			$MoveForm = new Phorm_Form('forms/control/categories.xml','move');
			$MoveForm->setAction($this->view->siteUrl().'/control/categories/move/categoryid/'.$CategoryInfo['categoryid']);
			$this->view->assign('MoveForm',$MoveForm);
			
			if(!empty($CategoryInfo['moduleid'])) {
				
				$Resource = new Phorm_Resource($CategoryInfo['moduleid']);
				$options = $Resource->getGridOptions('category');
				$options['url'] = '/control/resource/index/moduleid/'.$CategoryInfo['moduleid'].'/categoryid/'.$CategoryInfo['categoryid'].'/section/category/';
				$this->view->assign('ResourceDataTable',$this->view->DataGrid('ResourceDataTable',$options));
				
			}
			
			/**
			 * Обновление дерева разделов
			 */
			
			if(isset($this->_params['tree']) && $this->_params['tree']=='reload') {
				$js = 'window.parent.trees.categories.reload(\''.$this->view->siteUrl().'/control/?categoryid='.$CategoryInfo['categoryid'].'\');';
				$this->_boot->jquery->addOnload($js);
			}
			
		} else {
			
			// Ошибка 404... надо что-то придумать
			
		}
		
	}
	
	
	/**
	 * Создание раздела
	 *
	 * @return void
	 */
	
	public function addAction() {
		
		if(isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			if($this->Categories->isAllowedAction('add',$CategoryInfo['categoryid'])) {
		
				$form = $this->Categories->getCategoryForm($CategoryInfo['categoryid'],'add');
				
				$form -> setDefaults(
							array('moduleid'	 => $CategoryInfo['moduleid'],
								  'widgetssetid' => $CategoryInfo['widgetssetid'],
								  'visible'		 => $CategoryInfo['visible'],
								  'acl' 		 => $CategoryInfo['acl']));
				
				if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
						
					if($this->Categories->saveCategoryForm($form,array('parentid'=>$CategoryInfo['categoryid']))) {
						$User = new Phorm_User();
						$this->_usersession->UserData = $User->getUserInfo(array('userid'=>$this->_usersession->UserData['userid']));
						return $this->composeSuccessMessage('Раздел создан','/control/categories/view/categoryid/'.$CategoryInfo['categoryid'].'/tree/reload/');
					} else {
						$this->composeTransactionErrorMessage($this->Categories->_errors);
					}
					
				}
				
				$this->view->assign("Form",$form);
			
			} else {
				
				return $this->composeErrorMessage('Недостаточно прав для создания раздела','/control/categories/view/categoryid/'.$CategoryInfo['categoryid'].'/');
				
			}
		
		} else {
			
			return $this->composeErrorMessage('Раздел с указанным Id не найден','/control/categories/');
			
		}
		
	}
	
	
	/**
	 * Редактирование раздела
	 *
	 * @return void
	 */
	
	public function editAction() {
		
		if(isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			if($this->Categories->isAllowedAction('edit',$CategoryInfo['categoryid'])) {
		
				$form = $this->Categories->getCategoryForm($CategoryInfo['categoryid'],'edit');
				$form -> setDefaults($CategoryInfo);
				
				if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
						
					if($this->Categories->saveCategoryForm($form,$CategoryInfo['categoryid'])) {
						$User = new Phorm_User();
						$this->_usersession->UserData = $User->getUserInfo(array('userid'=>$this->_usersession->UserData['userid']));
						return $this->composeSuccessMessage('Изменения внесены','/control/categories/view/categoryid/'.$CategoryInfo['categoryid'].'/tree/reload/');
					} else {
						$this->composeTransactionErrorMessage($this->Categories->_errors);
					}
					
				}
				
				$this->view->assign("Form",$form);
			
			} else {
				
				return $this->composeErrorMessage('Недостаточно прав для внесения изменений','/control/categories/view/categoryid/' . $CategoryInfo['categoryid'] . '/');
				
			}
		
		} else {
			
			return $this->composeErrorMessage('Раздел с указанным Id не найден','/control/categories/');
			
		}
		
	}
	
	
	/**
	 * Удаление раздела
	 *
	 * @return void
	 */
	
	public function deleteAction() {
		
		if(isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			$redirect = '/control/categories/view/categoryid/' . $CategoryInfo['cparent'] . '/';
			
			if($this->Categories->isAllowedAction('delete',$CategoryInfo['categoryid'])) {
			
				if($this->Categories->deleteCategory($CategoryInfo)) {
					return $this->composeSuccessMessage('Выбранный раздел удален',$redirect.'/tree/reload/');
				} else {
					return $this->composeErrorMessage('Не удалось удалить раздел',$redirect);
				}
			
			} else {
				
				return $this->composeErrorMessage('Недостаточно прав для удаления раздела',$redirect);
				
			}
			
		} else {
			
			return $this->composeErrorMessage('Раздел с указанным Id не найден','/control/categories/');
			
		}
		
	}
	
	
	/**
	 * Перемещение раздела
	 *
	 * @return void
	 */
	
	public function moveAction() {
		
		if(isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			$redirect = '/control/categories/view/categoryid/' . $CategoryInfo['categoryid'] . '/';
		
			if(isset($this->_params['moveto']) && $CategoryToInfo = $this->Categories->getCategoryInfo($this->_params['moveto'])) {
				
				if($this->Categories->isAllowedAction('move',$CategoryInfo['categoryid'])) {
				
					if($this->Categories->moveCategory($CategoryInfo,$CategoryToInfo)) {
						return $this->composeSuccessMessage('Изменения внесены',$redirect . '/tree/reload/');
					} else {
						return $this->composeErrorMessage('Раздел с указанным Id не найден',$redirect);
					}
				
				} else {
					
					return $this->composeErrorMessage('Недостаточно прав для переноса раздела',$redirect);
					
				}
				
			} else {
				
				return $this->composeErrorMessage('Не найден раздел для переноса',$redirect);
				
			}
			
		} else {
			
			return $this->composeErrorMessage('Раздел с указанным Id не найден','/control/categories/');
			
		}
		
	}
	
	
	/**
	 * Смещение раздела
	 *
	 * @return void
	 */
	
	public function shiftAction() {
		
		if(isset($this->_params['direction']) && isset($this->_params['categoryid']) && $CategoryInfo = $this->Categories->getCategoryInfo($this->_params['categoryid'])) {
			
			$redirect = '/control/categories/view/categoryid/' . $CategoryInfo['categoryid'] . '/';
			
			if($this->Categories->isAllowedAction('shift',$CategoryInfo['categoryid'])) {
			
				if($this->Categories->changePosition($CategoryInfo,$this->_params['direction'])) {
					return $this->composeSuccessMessage('Изменения внесены',$redirect . 'tree/reload/');
				} else {
					return $this->composeErrorMessage('Невозможно перенести выбранный раздел',$redirect);
				}
			
			} else {
				
				return $this->composeErrorMessage('Недостаточно прав для переноса раздела',$redirect);
				
			}
			
		} else {
			
			return $this->composeErrorMessage('Раздел с указанным Id не найден','/control/categories/');
			
		}
		
	}
	
}